<?php

namespace App\Repository;

use App\Libs\PhpOffice\Excel;
use App\Models\Orders\OrdersModel;
use App\Models\Service\ServiceCallModel;
use App\Models\Service\ServiceCallTaskModel;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

class UploadExcelRepository extends BaseRepository
{
    private $logName = 'ExcelUploadLog';
    private $log;
    private $type, $willUpdateId, $postData;

    public function __construct()
    {
        $this->log = new Logger($this->logName);
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/' . $this->logName . '.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        ini_set('max_execution_time', 0);
        parent::__construct();
    }

    public function handleCallTaskData($extraData = [])
    {
//        已上传的文件地址
        $path = public_path($extraData['file_src']);
        if (!file_exists($path)) {
            $this->log->info('文件不存在:' . $path);
            return $this->returnMsg(100, '文件不存在:' . $path);
        }
        $ExcelClient = new Excel();

        $result = $ExcelClient->importFile($path, ['ordersno', 'weight', 'speech']);
        if (empty($result['data'])) {
            $this->log->info('数据为空:' . $path);
            return $this->returnMsg(1, '数据为空');
        }
        $inData = ['type' => 1, 'users_id' => $extraData['user']['id'] ?? 0, 'title' => '上传外呼' . date('YmdHis'), 'created_at' => date('Y-m-d H:i:s')];
        $inData['weight'] = $result['data'][0]['weight'] ?? 0;
        $inData['speech'] = $result['data'][0]['speech'] ?? '';
        $ordersNoArray = [];
        foreach ($result['data'] as $key => $v) {
            if (!empty($v['ordersno'])) {
                $ordersNoArray[] = $v['ordersno'];
            }
        }
        if (empty($ordersNoArray)) {
            $this->log->info('订单为空:' . $path);
            return $this->returnMsg(1, '订单数据为空');
        }
//        查询这些订单,做归属人
        $ModelOrders = new OrdersModel();
        $where = [];
//            根据任务归属客服找定单
        $where['egt']['service_user_id'] = 0;
        $where['in']['ordersno'] = $ordersNoArray;
        $works = [];
        foreach ($ModelOrders->searchWhere($where)->select(['id', 'ordersno', 'service_user_id'])->page(1, 5000)->cursor() as $row) {
            $works[$row['service_user_id']][] = $row;
        }
        if (empty($works)) {
            $this->log->info('客服归属订单数据为空:' . json_encode($where));
            return $this->returnMsg(1, '客服归属订单数据为空');
        }
//        自动根据客服分组
        $insertData = [];
        $ModelCallTask = new ServiceCallTaskModel();
        foreach ($works as $service_user_id => $worksNo) {
            $groups = $inData;
            $groups['service_user_id'] = $service_user_id;
//            //            记录要做的订单
//            $groups['orders_condition']['works'] = $worksNo;
//            //            已完成的订单记录
//            $groups['orders_condition']['done'] = [];
            $groups['orders_condition']['file_name'] = $extraData['file_name'];
            $groups['orders_condition']['file_src'] = $extraData['file_src'];
            $groups['orders_condition'] = json_encode($groups['orders_condition']);
            $taskId = $ModelCallTask->insertGetId($groups);
            foreach ($worksNo as $k => $row) {
                $callData = [
                    'call_task_id' => $taskId,
                    'ordersno' => $row['ordersno'],
                    'orders_id' => $row['id'],
                    'service_user_id' => $service_user_id,
                    'status' => 0,
                    'created_at' => date('Y-m-d H:i:s')
                ];
                $insertData[] = $callData;
            }
        }
        unset($inData, $ordersNoArray);
        if (empty($insertData)) {
            $this->log->info('任务记录表数据为空,不能记录具体外呼订单');
            return $this->returnMsg(2, '任务记录表数据为空,不能记录具体外呼订单');
        }
        $ModelServiceCall = new ServiceCallModel();
        $result = $ModelServiceCall->insert($insertData);
        if (empty($result)) {
            $this->log->info('任务保存失败:' . $this->getLastSql());
            return $this->returnMsg(2, '任务保存失败');
        }
        return $this->returnMsg(200, '任务保存成功', ['id' => $result]);
    }

}
